/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.duduso.conferencia_claro_desktop.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 *
 * @author duduso
 */
public class ZipUtils {

    private static final Integer TAMANHO_BUFFER = 2048;

    public static void criarAquivoZip(String zipFileName, List<File> inputFiles) throws Exception {

        FileInputStream streamEntrada = null;
        FileOutputStream destino = null;
        BufferedInputStream origem = null;
        ZipOutputStream saida = null;

        if(!zipFileName.contains(".zip")){
                zipFileName = zipFileName + ".zip";
        }
        
        byte dados[] = new byte[TAMANHO_BUFFER];

        try {

                destino = new FileOutputStream(zipFileName);
                saida = new ZipOutputStream(new BufferedOutputStream(destino));
                
                for(File file : inputFiles){
                        streamEntrada = new FileInputStream(file);
                        origem = new BufferedInputStream(streamEntrada, TAMANHO_BUFFER );
                        ZipEntry entrada = new ZipEntry(file.getName());
                        saida.putNextEntry(entrada);
                        int bytesLidos = 0;
                        while((bytesLidos = origem.read(dados, 0, TAMANHO_BUFFER)) != -1) {
                                saida.write(dados, 0, bytesLidos);
                        }
                        origem.close();
                }
                
                saida.close();

        } finally {

                if (streamEntrada != null){
                        streamEntrada.close();
                }

                if (destino != null) {
                        destino.close();
                }

        }

    }
}
